<?php

	include_once("cmsConfig.php");

	// this thing performs the async delete action....


	// first we need to try and look up the document that we want to remove the binary data from..
	// and then check that we are allowed to do so :D

	// then we get the binary data and fire a delete at it..

	$documentCode = extractNumberWithKeyFromArray('documentCode', $_REQUEST);
	$elementId = extractNumberWithKeyFromArray('elementId', $_REQUEST);
	
	$error = null;
	
	
	//get the document and check permissions???
	$document = null;
	if  ( !is_null($documentCode) && !is_null($elementId) ){
			$document = $cmsDocument->openDocument( $documentCode );
	} else {
		$error .= "elementId and documentCode are required<br />";		
	}
	
	//get a formDescriptor for use with the formElement.. 
	$formTableWriter = null;
	$formDescriptor = null;
	if ( !is_null($document) ){
		//create an instance of the form element thing...
		$formTableWriter = new CmsTableWriter("formdescriptor", $db);
		$formDescriptor = $formTableWriter->readItem( $document->formid );
	} else {
		$error .= "No document found<br />";
	}

	//get a form element .. so we can map back into the actual documnet
	$formElement = null;
	if (!is_null($formDescriptor)){
		$formElement = new CmsFormElement( $formDescriptor, $db);
	} else {
		$error .= "Could not load form descriptor<br />";
	}

	// look up the master field here.. so that we can work out what record in the doucment needs updating
	$elementDescriptor = null;
	if (!is_null($formElement)){
		
		$elementDescriptor = $formElement->getElementDescriptor( $elementId );
		
	} else {
		$error .= "No formElement created<br>";		
	}
		
		
	if (!is_null($elementDescriptor )){
		
		//put in the magic commit/rollback goodness here..
		if (CMS_WRITER_ENABLE_TRANSACTIONS ){
			$db->setAutoCommit( false );			
		}
		// delete the binary data.

		// we need to build a query
		$query = "DELETE FROM binarydata WHERE documentcode='$documentCode' and elementid='$elementId'";
		$res = $db->executeQuery( $query );
		if (!$res) {
			$error .="could not delete binary data";
		} else {
			//next update the content/document..
			$query = "UPDATE content SET $elementDescriptor->name=NULL WHERE documentcode=$documentCode";
			$res = $db->executeQuery( $query );
			clearItemsFromCacheWithDocumentCode($documentCode, CMS_BINARY_CACHE_PATH);
			//return the happyness		
			if (!$res) {
				$error .="could not update document data";
			}
		}
	} else {
		$error .= "Unable to lookup element descriptor";
	}

	//roll back here..

	if (is_null($error)){
		echo "$elementDescriptor->name";
		if (CMS_WRITER_ENABLE_TRANSACTIONS ){
			$db->commit();
		}
	}else {	
		if (CMS_WRITER_ENABLE_TRANSACTIONS ){
			$db->rollback();
		}
		//if we get here.. something has perhaps not gone to plan...
		header("HTTP/1.1 404 Not Found");
		echo "FAILED - (" . $error . ")";
	
	}
	if (CMS_WRITER_ENABLE_TRANSACTIONS ){
		$db->setAutoCommit( true );			
	}
?>